package com.ias.common.result;

import com.ias.common.utils.page.PageUtil;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;
import java.util.List;

/**
 * 分页结果封装类
 * 
 * @author IAS Team
 * @since 1.0.0
 */
@Data
public class PageResult<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;
    
    /**
     * 数据列表
     */
    private List<T> records;
    
    /**
     * 总记录数
     */
    private Long total;
    
    /**
     * 当前页码
     */
    private Long current;
    
    /**
     * 每页大小
     */
    private Long size;
    
    /**
     * 总页数
     */
    private Long pages;
    
    /**
     * 是否有上一页
     */
    private Boolean hasPrevious;
    
    /**
     * 是否有下一页
     */
    private Boolean hasNext;
    
    public PageResult() {
    }
    
    public PageResult(List<T> records, Long total, Long current, Long size) {
        this.records = records;
        this.total = total;
        this.current = current;
        this.size = size;
        this.pages = calculatePages(total, size);
        this.hasPrevious = current > 1;
        this.hasNext = current < this.pages;
    }

    public static <T> PageResult<T> success(Object result) {
        if (result == null) {
            throw new IllegalArgumentException("Result cannot be null");
        }
        try {
            return PageUtil.convertFromIPage(result);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert page result", e);
        }
    }


    /**
     * 计算总页数
     */
    private Long calculatePages(Long total, Long size) {
        if (total == null || total == 0 || size == null || size == 0) {
            return 0L;
        }
        return (total + size - 1) / size;
    }
    
    /**
     * 创建分页结果
     */
    public static <T> PageResult<T> of(List<T> records, Long total, Long current, Long size) {
        return new PageResult<>(records, total, current, size);
    }
    
    /**
     * 创建空分页结果
     */
    public static <T> PageResult<T> empty(Long current, Long size) {
        return new PageResult<>(List.of(), 0L, current, size);
    }
} 